package com.tbl.modules.wms.controller.stock;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.tbl.common.utils.DateUtils;
import com.tbl.common.utils.PageTbl;
import com.tbl.common.utils.PageUtils;
import com.tbl.modules.platform.constant.MenuConstant;
import com.tbl.modules.platform.controller.AbstractController;
import com.tbl.modules.platform.entity.system.User;
import com.tbl.modules.platform.service.system.RoleService;
import com.tbl.modules.platform.service.system.UserService;
import com.tbl.modules.wms.constant.Constant;
import com.tbl.modules.wms.entity.baseinfo.Warehouse;
import com.tbl.modules.wms.entity.inventory.Inventory;
import com.tbl.modules.wms.service.baseinfo.WarehouseService;
import com.tbl.modules.wms.service.inventory.InventoryService;
import com.tbl.modules.wms.service.move.MoveStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 盘点计划
 * @author 70486
 */
@Controller
@RequestMapping(value = "/inventoryPlan")
public class InventoryPlanController extends AbstractController {

    /**
     * 盘点计划服务类
     */
    @Autowired
    private InventoryService inventoryService;
    /**
     * 仓库
     */
    @Autowired
    private WarehouseService warehouseService;
    /**
     * 人员
     */
    @Autowired
    private UserService userService;
    /**
     * 角色接口
     */
    @Autowired
    private RoleService roleService;
    /**
     * 移库处理
     */
    @Autowired
    private MoveStorageService moveStorageService;

    /**
     * 跳转到盘点计划列表页面
     * @return ModelAndView
     */
    @RequestMapping(value = "/toList")
    public ModelAndView toList() {
        ModelAndView mv = this.getModelAndView();
        mv.addObject("operationCode", roleService.selectOperationByRoleId(getSessionUser().getRoleId(), MenuConstant.inventoryPlan));
        mv.setViewName("techbloom/stock/inventoryPlan/inventoryPlan_list");
        return mv;
    }

    /**
     * 盘点计划获取列表数据
     * @param queryJsonString
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/list.do")
    @ResponseBody
    public Map<String, Object> list(String queryJsonString) {
        Map<String, Object> map = new HashMap<>(2);
        if (!StringUtils.isEmpty(queryJsonString)) {
            map = JSON.parseObject(queryJsonString);
        }
        PageTbl page = this.getPage();
        String sortName = page.getSortname();
        if (StringUtils.isEmpty(sortName)) {
            sortName = "";
            page.setSortname(sortName);
        }
        String sortOrder = page.getSortorder();
        if (StringUtils.isEmpty(sortOrder)) {
            sortOrder = "desc";
            page.setSortorder(sortOrder);
        }
        PageUtils pageInventory = inventoryService.getInventoryPlanList(page, map);
        page.setTotalRows(pageInventory.getTotalCount() == 0 ? 1 : pageInventory.getTotalCount());
        map.put("rows", pageInventory.getList());
        executePageMap(map, page);
        return map;
    }

    /**
     * 弹出到添加/编辑页面
     * @param id 盘点计划主键
     * @return ModelAndView
     */
    @RequestMapping(value = "/toAdd.do")
    @ResponseBody
    public ModelAndView toAdd(Long id) {
        ModelAndView mv = new ModelAndView();
        Inventory inventory;
        //表示进入的是添加的界面
        if (id == -1) {
            inventory = new Inventory();
            inventory.setId(Long.valueOf("-1"));
            inventory.setEbsCode(null);
        } else {
            //表示进入的是编辑的界面
            //通过ID获取数据
            inventory = inventoryService.selectById(id);
            List<Map<String, Object>> mapList = warehouseService.selectMaps(new EntityWrapper<Warehouse>()
            		.eq(inventory.getWarehousecode()!=null,"code", inventory.getWarehousecode()));
            inventory.setWarehousename(mapList.size()>0?(mapList.get(0).get("NAME") != null ? mapList.get(0).get("NAME").toString() : ""):"");
        }

        //根据用户所属厂区获取厂区信息列表  okk
        mv.addObject("factoryCodeList", inventoryService.getFactoryList(Arrays.asList(getSessionUser().getFactoryCode().split(","))));
        mv.addObject("it", inventory);
        mv.setViewName("techbloom/stock/inventoryPlan/inventoryPlan_edit");
        return mv;
    }

    /**
     * 保存盘点计划
     * @param inventory 盘点计划信息
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public Map<String, Object> save(Inventory inventory) {
        Map<String, Object> map = Maps.newHashMap();
        //先判断同一ebs盘点单号下是否有重复的仓库，不能新增重复的仓库
        StringBuffer existedWarehouseBuffer = new StringBuffer();
        List<Inventory> inventoryList = inventoryService.selectList(new EntityWrapper<Inventory>().eq("EBS_CODE", inventory.getEbsCode()));
        //如果是修改，去除本身
        if (inventory.getId() != -1){
            inventoryList.removeIf(inv -> inv.getId().equals(inventory.getId()));
        }
        //仓库主键
        inventoryList.forEach(inv -> existedWarehouseBuffer.append(inv.getFactorycode()).append(","));
        //当前盘点单号下已经存在的仓库主键
        List<String> existedFactoryList = new ArrayList<>(Arrays.asList(existedWarehouseBuffer.toString().split(",")));
        //要新增的仓库主键
        List<String> addedFactoryList = new ArrayList<>(Arrays.asList(inventory.getFactorycode().split(",")));
        //判断当前单号下已经存在的厂区是否包含要新增的
        existedFactoryList.retainAll(addedFactoryList);
        if (existedFactoryList.size()>0){
            map.put("result", false);
            map.put("msg", "该盘点单号下包含这些仓库，不能添加重复的仓库，请核对！");
            return map;
        }

        //如果等于-1的话，则表示当前是添加
        if (inventory.getId() == -1) {
            int maxNo = inventoryService.getMaxCode()+1;
            String serial = new DecimalFormat("0000").format(maxNo);

            inventory.setCode("PD" + DateUtils.longToStringNY(System.currentTimeMillis()) + serial);
            inventory.setState(Constant.LONG_ZERO);
            inventory.setCreater(getSessionUser().getUserId().toString());
            inventory.setCreatetime(new Date());
            inventoryService.insert(inventory);
            moveStorageService.updateSerial(serial, "inventory");

            map.put("code", maxNo);
            // 主键
            map.put("id", inventory.getId());
        } else {
            inventoryService.updateById(inventory);
        }

        map.put("result", true);
        map.put("msg", "保存成功！");
        return map;
    }

    /**
     * 删除盘点任务
     * @param ids 盘点计划主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/deleteCars.do")
    @ResponseBody
    public Map<String, Object> deleteCars(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        boolean result = inventoryService.deleteBatchIds(Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()));
        map.put("result", result);
        map.put("msg", result ? "删除成功！" : "删除失败！");
        return map;
    }

    /**
     * 根据主键查询盘点计划
     * @param id 库存盘点--盘点计划主键
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getInventoryById")
    @ResponseBody
    public Map<String, Object> getInventoryById(Long id) {
        Map<String, Object> map = new HashMap<>(4);
        //-1表示新增
        if(id != -1) {
	        Inventory inventory = inventoryService.selectById(id);
	        map.put("warehouseList",warehouseService.selectList(new EntityWrapper<Warehouse>().in("CODE", inventory.getWarehousecode())));
            map.put("userList",userService.selectBatchIds(Arrays.asList(inventory.getUserId().split(","))));
            map.put("factoryList",warehouseService.selectBatchIds(Arrays.stream(inventory.getFactorycode().split(",")).map(Long::parseLong).collect(Collectors.toList())));
	        map.put("it", inventory);
        }
        return map;
    }

    /**
     * 选择人员
     * @param queryString 模糊查询条件
     * @param pageSize 页大小
     * @param pageNo 页码
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getPerson")
    @ResponseBody
    public Map<String, Object> getPerson(String queryString,int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>(3);
        List<Map<String, Object>> mapList = new ArrayList<>();
        map.put("page", pageNo);
        map.put("limit", pageSize);
        map.put("queryString", queryString);
        Page<User> pageList = userService.getSelectUserList(map);
        Map<String, Object> objMap;
        for (int i = 1; i <= pageList.getRecords().size(); i++) {
            objMap = new HashMap<>(2);
            objMap.put("id", pageList.getRecords().get(i - 1).getUserId());
            objMap.put("text", pageList.getRecords().get(i - 1).getText());
            mapList.add(objMap);
        }
        map.put("result", mapList);
        map.put("total", pageList.getTotal());
        return map;
    }

    /**
     * 选择仓库
     * @param queryString 查询条件
     * @param factoryCode 厂区编码
     * @param pageSize 每页显示数量
     * @param pageNo 页数
     * @return Map<String,Object>
     */
    @RequestMapping(value = "/getWarehouse")
    @ResponseBody
    public Map<String, Object> getWarehouse(String queryString,String factoryCode,int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<>(6);
        List<Map<String, Object>> mapList = new ArrayList<>();
        map.put("queryString", queryString.toUpperCase());
        map.put("page", pageNo);
        map.put("limit", pageSize);
        map.put("factoryCode", factoryCode);
        //获取对应仓库的数据
        Page<Warehouse> pageList = warehouseService.getSelectWarehouseList(map);
        Map<String, Object> objMap;
        for (int i = 1; i <= pageList.getRecords().size(); i++) {
            objMap = new HashMap<>(2);
            objMap.put("id", pageList.getRecords().get(i - 1).getCode());
            objMap.put("text", pageList.getRecords().get(i - 1).getCode());
            mapList.add(objMap);
        }
        map.put("result", mapList);
        map.put("total", pageList.getTotal());
        return map;
    }

    /**
     * 跳转到盘点审核页面
     * @param id
     * @return ModelAndView
     */
    @RequestMapping(value = "/toView.do")
    @ResponseBody
    public ModelAndView toView(Long id) {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("techbloom/demo/stock/inventoryPlan/inventoryPlan_view");
        return mv;
    }

    /**
     * 提交（改变盘点计划状态）
     * @param ids 盘点计划主键
     * @return Map<String, Object>
     */
    @RequestMapping(value = "/submit")
    @ResponseBody
    public Map<String, Object> submit(String ids) {
        Map<String, Object> map = new HashMap<>(2);
        List<Inventory> entityList = inventoryService.selectBatchIds(Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList()));
        entityList.forEach(inventory -> inventory.setState(1L));
        boolean result = inventoryService.updateBatchById(entityList);
        map.put("result", result);
        map.put("msg", result ? "提交成功！" : "提交失败！");
        return map;
    }

    /**
     * 导出盘点审核明细
     */
    @RequestMapping(value = "/toExcel.do", method = RequestMethod.POST)
    @ResponseBody
    public void toExcel() {
        inventoryService.toExcel(response, request.getParameter("ids"), inventoryService.getAllLists(request.getParameter("ids"), getUserId()));
    }

}
